package cycling.taxi.com.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import cycling.taxi.com.IConstants;
import cycling.taxi.com.R;
import cycling.taxi.com.bean.PositionInfo;
import cycling.taxi.com.person.ExitApplication;
import cycling.taxi.com.request.Config;
import cycling.taxi.com.request.RM;
import cycling.taxi.com.request.RequestBean;
import cycling.taxi.com.request.RequestCallback;
import cycling.taxi.com.request.RequestParams;
import cycling.taxi.com.request.RequestUtil;
import cycling.taxi.com.utils.LogUtil;
import cycling.taxi.com.utils.MD5Util;
import cycling.taxi.com.utils.SPUtil;
import cycling.taxi.com.utils.Urls;

public class TestActivity extends Activity implements View.OnClickListener, RequestCallback {
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private Polyline mPolyline;
    private String historyInfo;
    ArrayList<PositionInfo> infos;
    private ImageView back;
    private TextView title_text;
    private LocationClient mLocClient;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trajectory);
        Intent intent=getIntent();
        Bundle bundle=intent.getExtras();
        String str=bundle.getString("history");
        historyInfo=str;
        /////////////
        mMapView = (MapView) findViewById(R.id.bmapView);
        mMapView.onCreate(this, savedInstanceState);
        mBaiduMap = mMapView.getMap();
        back= (ImageView) findViewById(R.id.back);
        title_text= (TextView) findViewById(R.id.title_text);
        title_text.setText("行车轨迹");
        back.setOnClickListener(this);
        /////////////
        DrawTrajectory();
        ExitApplication.getInstance().addActivity(this);

    }
    private void doGetCurrentPT() {
        // 设置是否允许定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位服务的客户端。
        mLocClient = new LocationClient(this);
        // 注册定位监听函数
        mLocClient.registerLocationListener(new BDLocationListener() {

                                                @Override
                                                public void onReceiveLocation(BDLocation location) {
                                                    // map view 销毁后不在处理新接收的位置
                                                    if (location == null || mMapView == null)
                                                        return;
                                                    // 定位数据:accuracy:定位精度,direction:GPS定位时方向角度.百度纬度坐标,百度经度坐标
                                                    MyLocationData locData = new MyLocationData.Builder()
                                                            .accuracy(location.getRadius())
                                                            // 此处设置开发者获取到的方向信息，顺时针0-360
                                                            .direction(100).latitude(location.getLatitude())
                                                            .longitude(location.getLongitude()).build();
                                                    // 设置定位数据, 只有先允许定位图层后设置数据才会生效
                                                    mBaiduMap.setMyLocationData(locData);
                                                        LatLng ll = new LatLng(location.getLatitude(), location
                                                                .getLongitude());
                                                        // 设置地图新状态
                                                        MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                                                        // 改变地图状态
                                                        mBaiduMap.animateMapStatus(u);

                                                }
                                                public void onConnectHotSpotMessage(String arg0, int arg1) {
                                                }
                                            }

        );
        // 配置定位参数
        LocationClientOption option = new LocationClientOption();
        // 打开gps进行定位
        option.setOpenGps(true);// 打开gps
        // 设置坐标类型
        option.setCoorType("bd09ll"); // 设置坐标类型
        // 设置扫描间隔，单位是毫秒
        option.setScanSpan(1000);
        // 定位服务客户端设置配置
        mLocClient.setLocOption(option);
        // 定位服务开启
        mLocClient.start();
    }
    private void DrawTrajectory() {
        //获取服务器数据
        String mobile= SPUtil.getInstance().getData("phone");
        String password= SPUtil.getInstance().getData("password");
        RequestParams params = new RequestParams.Builder()
                .putParam("mobile",mobile)
                .putParam("password", MD5Util.MD5Encode(password))
                .putParam("beanJson",SPUtil.getInstance().getData("beanJson"))
                .putParam("history",historyInfo)
                .build();

        //开始请求发送数据到服务器服务器
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String url = Urls.getTrajectory();//轨迹的url路径

        RequestUtil.requestData(requestQueue,
                IConstants.TRAJECTORY,
                url,
                RM.GET,
                RequestBean.class,
                params,
                this);

    }
    private void drawPolyLine() {

        List<LatLng> polylines = new ArrayList<>();
        BitmapDescriptor bitmapstart = BitmapDescriptorFactory.fromResource(R.drawable.ic_line_stop_red);
        DecimalFormat df= new DecimalFormat("######0.000000");

        OverlayOptions startoption = new MarkerOptions().position(new LatLng(Double.parseDouble(df.format(infos.get(0).getLatitude())),Double.parseDouble(df.format(infos.get(0).getLongitude())))).icon(bitmapstart);//构建MarkerOption，用于在地图上添加Marker
        mBaiduMap.addOverlay(startoption);//在地图上添加Marker，并显示
        for (int index = 0; index < infos.size(); index++) {
            LatLng pt = new LatLng(Double.parseDouble(df.format(infos.get(index).getLatitude())), Double.parseDouble(df.format(infos.get(index).getLongitude())));
            polylines.add(pt);
        }
        PolylineOptions polylineOptions = new PolylineOptions().points(polylines).width(10).color(Color.RED);
        mPolyline = (Polyline) mBaiduMap.addOverlay(polylineOptions);
        BitmapDescriptor bitmapend = BitmapDescriptorFactory.fromResource(R.drawable.ic_line_star_blue);
        OverlayOptions endoption = new MarkerOptions().position(new LatLng(Double.parseDouble(df.format(infos.get(infos.size()-1).getLatitude())),Double.parseDouble(df.format(infos.get(infos.size()-1).getLongitude())))).icon(bitmapend);
        mBaiduMap.addOverlay(endoption);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        mBaiduMap.clear();
    }
    @Override
    public void requestSuccess(RequestBean bean, Config config) {
        LogUtil.e(bean.beanJson);
        infos=new Gson().fromJson(bean.beanJson,new TypeToken<List<PositionInfo>>(){}.getType());
        LatLng pt = new LatLng(infos.get(0).getLatitude(), infos.get(0).getLongitude());
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(pt);
        builder.zoom(14.0f);
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        drawPolyLine();

        mMapView.showZoomControls(false);

    }

    @Override
    public void requestFail(RequestBean bean, Config config) {
        doGetCurrentPT();
    }

    @Override
    public void requestTokenInvalid(String requestTag, Config config) {

    }

    @Override
    public void onClick(View v) {
        if (v.getId() ==R.id.back){
            finish();
        }
    }
}
